package com.shaokel.config.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import lombok.AllArgsConstructor;
import lombok.ToString;

/**
 * @author 少丶客
 * @ClassName LogAspect
 * @Description 日志切面
 * @Date 2020/6/22 20:04
 * @Vesion 1.0
 */
@Aspect
@Component
public class LogAspect {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.shaokel.controller.*.*(..))")   //切入点
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        log.info("----------doBefore----------");
        //获取HttpServletRequest
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String url = request.getRequestURI().toString();//获取url
        String ip = request.getRemoteAddr();//获取ip
        //获取类名和方法名
        String classMethod = joinPoint.getSignature().getDeclaringType() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();//获取方法参数
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        log.info("Request : {}",requestLog);
    }

    @After("log()")
    public void doAfter(){
        log.info("----------doAfter----------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doBefore(Object result){
        log.info("Result : {}" ,result);
    }

    @ToString
    @AllArgsConstructor
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;
    }

}